package com.hanshg.cherry.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hanshg.cherry.base.result.Results;
import com.hanshg.cherry.dto.LoginUser;
import com.hanshg.cherry.mapper.file.MailMapper;
import com.hanshg.cherry.model.SysMail;
import com.hanshg.cherry.service.mail.SysMailService;
import com.hanshg.cherry.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Base64;

/**
 * @author 柠檬水
 */
@Service
@Transactional
@Slf4j
public class SysMailServiceImpl implements SysMailService {

    @Autowired
    private MailMapper mailMapper;

    @Autowired
    private UserService userService;

    @Override
    public SysMail getSysMail() {
        QueryWrapper<SysMail> wrapper = new QueryWrapper<>();
        wrapper.eq("operation",getUserName());
        SysMail sysMail = mailMapper.selectOne(wrapper);
        if (sysMail != null) {
            sysMail.setPassword(new String(Base64.getMimeDecoder().decode(sysMail.getPassword())));
        }
        return sysMail;
    }

    @Override
    public Results saveMail(SysMail sysMail) {
        sysMail.setOperation(getUserName());
        sysMail.setPassword(new String(Base64.getMimeEncoder().encode(sysMail.getPassword().getBytes())));
        int i = mailMapper.insert(sysMail);
        if (i > 0) {
            return Results.success();
        }
        return Results.failure();
    }

    @Override
    public Results updateMail(SysMail sysMail) {
        sysMail.setOperation(getUserName());
        sysMail.setPassword(new String(Base64.getMimeEncoder().encode(sysMail.getPassword().getBytes())));
        int i = mailMapper.updateById(sysMail);
        if (i > 0) {
            return Results.success();
        }
        return Results.failure();
    }

    /**
     * 获取登录用户信息
     * @return
     */
    private String getUserName(){
        LoginUser loginUser = userService.getLoginUser();
        return loginUser.getUsername();
    }
}
